import { defineStore } from 'pinia';
import { getCurrentUserMenus } from '@/api/menu';

const result = [];
const retrievalRouter = (arr: Array<any>) => {
  for (const item of arr) {
    result.push(item)
    if (item.children && item.children.length) {
      result.concat(retrievalRouter(item.children))
    }
  }
  return result
}

const wls = ['notFound', 'workplace']

export const useMenuStore = defineStore('menu', {
  state: () => ({ menus: [], menuList: [] }),

  getters: {},

  actions: {
    //获取菜单
    async getMenu() {
      const moteMenus = (await getCurrentUserMenus({ page: 1, limit: 50 }));
      this.menus = moteMenus;
      this.menuList = retrievalRouter(moteMenus);
    },

    dynamicConfigApi(actions) {
      try {
        Object.keys(actions).forEach(key => {
          const action = actions[key];
          const menu = this.menuList.find(menu => action.permission.includes(menu['controller']))
          if (menu) {
            action.api = menu['after_route']
            action.method = menu['methods']
          }
        })
      } catch (e) {
        console.warn("动态配置api异常:", e)
      }
      return actions
    },

    validateRoutePermission(name) {
      if (wls.includes(name)) return true;
      const menu = this.menuList.find(item => item['front_route'] === name.toLowerCase());
      return !!menu;
    },

    cleanData() {
      this.$reset();
    }
  },
});
